iT邦幫忙

2024 iThome 鐵人賽

DAY 9
0
Software Development

從Servlet到Spring MVC系列 第 9

Day08 Servlet - ServletConfig and ServletContext

  • 分享至 

  • xImage
  •  

前言

0、創建module

請參考Day05創建module

一、ServletConfig

ServletConfig是為每一個Servlet專屬的設定檔,可以透過web.xml設定檔,再由web container初始化Servlet時透過GenericServlet init方法交給我們ServletConfig物件,由於GenericServlet也實作了ServletConfig interface我們可以透過定義好的方法取得container傳遞給我們的設定檔內容

  • getInitParameterNames()取得參數名稱enumeration物件
  • getServletContext()
  • getInitParameter(String name)透過key取出value值

(1) 創建DemoServletConfig

public class DemoServletConfig extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
        PrintWriter out = res.getWriter();
        out.println("keyA"+"=="+getInitParameter("keyA"));
        out.println("===========hello servletConfig==========");

        //取得所有初始化參數名稱
        Enumeration<String> initParameterNames = getServletConfig().getInitParameterNames();
        while (initParameterNames.hasMoreElements()) {
            String name = initParameterNames.nextElement();
            out.println(name + "==" + getServletConfig().getInitParameter(name));
        }
        out.println("===========hello servletConfig==========");
    }
}

修改web.xml設定檔,透過tag init-param設定Servlet初始參數

<web-app>
  <servlet>
    <servlet-name>DemoServletConfig</servlet-name>
    <servlet-class>com.swj.DemoServletConfig</servlet-class>
    <init-param>
      <param-name>keyA</param-name>
      <param-value>paramA</param-value>
    </init-param>
    <init-param>
      <param-name>keyB</param-name>
      <param-value>paramB</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>DemoServletConfig</servlet-name>
    <url-pattern>/DemoServletConfig</url-pattern>
  </servlet-mapping>
</web-app>

Demo

啟動server,訪問路徑http://localhost:8080/MyWebApp/DemoServletConfig
https://ithelp.ithome.com.tw/upload/images/20240923/201280847qdqsvHyQR.png

(2) 使用Annotation

首先先註解掉web.xml中的相關設定,再對DemoServletConfig進行修改

@WebServlet(value = "/DemoServletConfig",
            initParams = {@WebInitParam(name = "keyA",value = "annotationValueA"),
                    @WebInitParam(name = "keyB",value = "annotationValueB")})
public class DemoServletConfig extends HttpServlet {
  //略
}

Annotation Demo

https://ithelp.ithome.com.tw/upload/images/20240923/20128084QkR2j0Duci.png

二、ServletContext

ServletContext api doc提及此介面提供的方法是Servlet用來與Servlet Container溝通用的,既是溝通所以帶我們可以取得Container相關資訊,亦可對Container設定資訊,所以每個Servlet使用的是同一個ServletContext。我們可以透過下面3個API取得ServletContext

  • getServletContext()
  • getServletConfig().getServletContext()
  • ServletRequest.getServletContext()

創建DemoContextServlet

<web-app>
    <context-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </context-param>
    <context-param>
        <param-name>contextParamA</param-name>
        <param-value>contextValueA</param-value>
    </context-param>
    <servlet>
        <servlet-name>HelloContextServlet</servlet-name>
        <servlet-class>com.swj.DemoContextServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloContextServlet</servlet-name>
        <url-pattern>/DemoContextServlet</url-pattern>
    </servlet-mapping>
</web-app>
public class DemoContextServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
        PrintWriter out = res.getWriter();
        out.println("===========DemoContextServlet==========");
        //get ServletContext method
        ServletContext context1 = getServletContext();
        ServletContext context2 = getServletConfig().getServletContext();
        ServletContext context3 = req.getServletContext();
        out.println(context1 == context2);
        out.println(context2 == context3);
        out.println(context1);
        out.println("getEncoding use getInitParameter(\"encoding\")"+"=="+context1.getInitParameter("encoding"));
        Enumeration<String> initParameterNames = context1.getInitParameterNames();
        while (initParameterNames.hasMoreElements()) {
            String name = initParameterNames.nextElement();
            out.println(name + "==" + getServletConfig().getInitParameter(name));
        }
        out.println("===========DemoContextServlet==========");
    }
}

修改DemoServletConfig來確認是否兩個Servlet取得同一個ServletContext物件

@WebServlet(value = "/DemoServletConfig",
            initParams = {@WebInitParam(name = "keyA",value = "annotationValueA"),
                    @WebInitParam(name = "keyB",value = "annotationValueB")})
public class DemoServletConfig extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
      //略
      out.println("ServletContext:"+getServletContext());
      out.println("===========hello servletConfig==========");   
    }
}

Demo

demo取得context中的初始參數
https://ithelp.ithome.com.tw/upload/images/20240923/20128084MDJIxWCXKU.png

DemoServletConfig與DemoContextServlet取得同一個ServletContext物件
https://ithelp.ithome.com.tw/upload/images/20240923/20128084fR0ia5ObKV.png

小結

web.xml是用來跟web container溝通的地方,他為每一個Servlet提供專屬的設定檔配置物件ServletConfig,也為所有的Servlet提供共用設定配置物件ServletContext。
https://ithelp.ithome.com.tw/upload/images/20240923/20128084n2xaXDWXQn.png

Reference


上一篇
Day07 Servlet - Servlet Structure
下一篇
Day09 Servlet - ServletContext API
系列文
從Servlet到Spring MVC36
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言